package com.sl.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.itheima.auth.factory.AuthTemplateFactory;
import com.itheima.auth.sdk.common.Result;
import com.itheima.auth.sdk.dto.AuthUserInfoDTO;
import com.itheima.auth.sdk.service.TokenCheckService;
import com.sl.gateway.config.MyConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * 后台管理员token拦截处理
 */
@Component
public class ManagerTokenGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> implements AuthFilter {

    @Resource
    private MyConfig myConfig;
    @Resource
    private TokenCheckService tokenCheckService;
    // 从nacos中获取有权限的用户
    @Value("${role.manager}")
    private List<Long> managerRoleList; // 允许登录到管理系统的角色列表

    @Override
    public GatewayFilter apply(Object config) {
        //由于实现了AuthFilter接口，所以可以传递this对象到TokenGatewayFilter中
        return new TokenGatewayFilter(this.myConfig, this);
    }

    @Override
    public AuthUserInfoDTO check(String token) {
        //校验token
        return tokenCheckService.parserToken(token);
    }

    @Override
    public Boolean auth(String token, AuthUserInfoDTO authUserInfoDTO, String path) {
        // 思路: 需要检查当前请求用户的角色, 如果该角色允许登录后台系统返回true, 否则返回false

        // 查询当前请求用户的角色
        Result<List<Long>> resultRole = AuthTemplateFactory.get(token).opsForRole()
                .findRoleByUserId(authUserInfoDTO.getUserId());
        List<Long> roleList = resultRole.getData();

        // 如何判断当前用户是否允许登录后台系统 ?
        // 取交集, 用于判断是否有登录的权限
        Collection<Long> intersection = CollUtil.intersection(roleList, managerRoleList);
        return CollUtil.isNotEmpty(intersection); // 如果不为空, 则证明有管理权限
        //        return true;
    }
}
